<template>
  <div>
    <van-nav-bar
      title="注册"
      left-text="返回"
    />
    <van-form ref="form" @submit="onSubmit">
      <van-field
        v-model="form.phone"
        name="phone"
        label="手机号"
        placeholder="请输入手机号"
        :rules="formRules.phone"
      />
      <van-field
        v-model="form.captcha"
        name="captcha"
        label="验证码"
        placeholder="请输入四位验证码"
      >
        <template #button>
          <van-button @click="sendCode" type="danger" plain native-type="button" size="small">发送验证码</van-button>
        </template>
      </van-field>
      <van-field
        v-model="form.password"
        type="password"
        name="password"
        label="密码"
        placeholder="请输入密码"
      />
      <van-field
        v-model="form.nickname"
        name="nickname"
        label="昵称"
        placeholder="请输入昵称"
      />
      <div style="margin: 16px;">
        <van-button color="linear-gradient(to right, #ff6034, #ee0a24)" round block native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { getMobileCode, reg } from '@/api/login.js'
import { Toast } from 'vant'
export default {
  data () {
    return {
      form: {
        phone: '',
        captcha: '',
        password: '',
        nickname: ''
      },
      formRules: {
        phone: [
          { required: true, message: '请填写手机号' },
          {
            validator: (val, rule, callback) => {
              const reg = /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/
              if (reg.test(val)) {
                return true
              } else {
                return false
              }
            },
            message: '手机号码格式不正确'
          }
        ]
      }
    }
  },

  created () {

  },

  methods: {
    async sendCode () {
      try {
        await this.$refs.form.validate('phone')
        const res = await getMobileCode({
          phone: this.form.phone
        })
        console.log(res)
        Toast.success('发送成功')
      } catch (err) {
        console.log(err)
      }
    },
    async onSubmit (value) {
      try {
        const res = await reg(value)
        console.log(res)
        if (res.data.code !== 200) {
          return Toast(res.data.message)
        }
        this.$router.back()
        Toast.success('注册成功')
      } catch (err) {
        console.dir(err)
        Toast(err.response.data.msg)
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
